package com.android.nodejs.livejs.activities;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.adapters.FriendAdapter;
import com.android.nodejs.livejs.base.BaseFragment;
import com.android.nodejs.livejs.constants.AddMessageConstants;
import com.android.nodejs.livejs.constants.DisplayConstants;
import com.android.nodejs.livejs.models.User;
import com.android.nodejs.livejs.utils.CommonUtil;

public class FriendFragment extends BaseFragment {
	private ListView mListView;
	private View mView;
	private EditText edtLastStatus;
	private Button btnPostLastStatus;
    
    private int user_id;
    private int friend_id;
    private String fullName;
    private String email;
    private String birthday;
    private int gender;
    private String strGender;
    private String status;
    private String last_status;
    
    private ProgressDialog progressDialog;
    private int numSelectedInListView;
    
    private FriendAdapter friendAdapter;
    private BufferedWriter w;
    
    private static final int REQUEST_CHAT = 101;

	@Override
	public void inits() {
		// nothing
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_friends, null);
		IntentFilter filterAddFriend = new IntentFilter("ADD_FRIEND");
	    getActivity().registerReceiver(new ListFriendsBroadCastReceiver(), filterAddFriend);
	    IntentFilter filterDeleteFriend = new IntentFilter("DELETE_FRIEND");
        getActivity().registerReceiver(new ListFriendsBroadCastReceiver(), filterDeleteFriend);
        IntentFilter filter = new IntentFilter("GET_GROUP_ID");
        getActivity().registerReceiver(new ListFriendsBroadCastReceiver(), filter);
		return mView;
	}

	@Override
	public void initComponents(View view) {
	    w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
		mListView = (ListView) view.findViewById(R.id.listFriends);
		mListView.setAdapter(null);
		friendAdapter = new FriendAdapter(getActivity(), MyApplication.LIST_FRIENDS);
		mListView.setAdapter(friendAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
                friend_id = ((User) mListView.getAdapter().getItem(position)).getId();
                //add to new group chat on server
                try {
                    w.write(AddMessageConstants.ADD_TO_GROUP);
                    w.write(AddMessageConstants.HAVE_NOT_GROUP + MyApplication.USER_CURRENT.getId() + "!!" + friend_id);
                    w.flush();
                } catch (IOException e) {
                    Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                    e.printStackTrace();
                }
                //start chat activity
                int friendId = ((User) mListView.getAdapter().getItem(position)).getId();
                String friendFullName = ((User) mListView.getAdapter().getItem(position)).getFullName();
                String friendAvatar = ((User) mListView.getAdapter().getItem(position)).getAvatar();
                Intent intentChat = new Intent();
                intentChat.setClass(getActivity(), ChatActivity.class);
                Bundle b = new Bundle();
                b.putInt("friend_id",  friendId);
                b.putString("friend_full_name",  friendFullName);
                b.putString("friend_avatar",  friendAvatar);
                intentChat.putExtras(b);
                getActivity().startActivityForResult(intentChat, REQUEST_CHAT);
            }
		});
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> adapter, View v, int position, long id) {
                numSelectedInListView = position;
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setItems(new String[] { "Delete this friend", "View Profile" }, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        user_id = MyApplication.USER_CURRENT.getId();
                        friend_id = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getId();
                        fullName = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getFullName();
                        email = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getEmail();
                        birthday = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getBirthday();
                        if(birthday.endsWith("Z")) {
                            birthday = CommonUtil.dateToString(((User) mListView.getAdapter().getItem(numSelectedInListView)).getBirthday());
                        }
                        gender = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getGender();
                        strGender = gender==1?"Male":"Female";
                        status = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getStatus();
                        last_status = ((User) mListView.getAdapter().getItem(numSelectedInListView)).getLastStatus();
                        if ("null".equals(status)) {
                            status = "No status";
                        }
                        switch (which) {
                            case 0:
                                AlertDialog.Builder adb=new AlertDialog.Builder(getActivity());
                                adb.setTitle("Delete confirm?");
                                adb.setMessage("Are you sure you want to delete this contact?");
                                adb.setNegativeButton("Cancel", null);
                                adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        progressDialog = ProgressDialog.show(getActivity(), "", "Deleting this friend...");
                                        try {
                                            //BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                                            w.write(AddMessageConstants.DELETE_FRIEND);
                                            w.write(user_id + "!!" + friend_id);
                                            w.flush();
                                            
                                            if (progressDialog.isShowing()) {
                                                progressDialog.dismiss();
                                            }
                                        } catch (IOException e) {
                                            Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                                            e.printStackTrace();
                                        }
                                    }});
                                adb.show();
                                break;
                            case 1:
                                CommonUtil.dialogNotify(getActivity(), "Name:\t\t\t"+fullName+"\nEmail:\t\t\t"+email+"\nBirthday:\t"+birthday+"\nGender:\t\t"+strGender+"\nStatus:\t\t"+status);
                                break;
                            default:
                                break;
                        }
                    }
                });
                dialog.show();
                return false;
            }
        });
		
		edtLastStatus = (EditText) view.findViewById(R.id.edtLastStatus);
		edtLastStatus.setText(MyApplication.USER_CURRENT.getLastStatus());
		edtLastStatus.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    CommonUtil.hideVirtualKeyboard(v);
                    processPostLastStatus();
                    return true;
                }
                return false;
            }
        });
		
		btnPostLastStatus = (Button) view.findViewById(R.id.btnLastStatus);
		btnPostLastStatus.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                CommonUtil.hideVirtualKeyboard(v);
                processPostLastStatus();
            }
        });
	}
	
	/**
	 * post last status to server
	 */
	private void processPostLastStatus() {
	    String strSearch = edtLastStatus.getText().toString().trim();
        if(MyApplication.USER_CURRENT.getLastStatus().equals(strSearch) == false) {
            try {
                //BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                w.write(AddMessageConstants.POST_LAST_STATUS);
                w.write(MyApplication.USER_CURRENT.getId() + "!!" + strSearch);
                w.flush();

            } catch (IOException e) {
                Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getActivity(), "Does not change anything!", Toast.LENGTH_LONG).show();
        }
	}

	@Override
	public void addListenners() {
		// nothing
	}
	
	/** Show Toast message */
    private Handler toastHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_DELETE_FRIEND_FAIL, Toast.LENGTH_LONG).show();
            } else if (msg.what == 1) {
                MyApplication.LIST_FRIENDS.remove(numSelectedInListView);
                mListView.setAdapter(friendAdapter);
                Toast.makeText(getActivity(), DisplayConstants.DIS_DELETED_FRIEND, Toast.LENGTH_LONG).show();
            } else if (msg.what == 2) {
                CommonUtil.dialogNotify(getActivity(), DisplayConstants.DIS_CONNECT_SERVER_FAIL);
            } else if (msg.what == 3) {
                Toast.makeText(getActivity(), DisplayConstants.DIS_POST_LAST_STATUS_FAIL, Toast.LENGTH_LONG).show();
            } else if (msg.what == 4) {
                MyApplication.USER_CURRENT.setLastStatus(edtLastStatus.getText().toString().trim());
                Toast.makeText(getActivity(), DisplayConstants.DIS_POSTED_LAST_STATUS, Toast.LENGTH_LONG).show();
            } else if (msg.what == 5) {
                mListView.setAdapter(friendAdapter);
            } else if (msg.what == 6) {
                // create item in ChatFragment
                Bundle data = msg.getData();
                Intent intent = new Intent();
                intent.setAction("MESSAGE_CHAT");
                intent.putExtra("idGroup", data.getString("idGroup"));
                intent.putExtra("idSender", ""+MyApplication.USER_CURRENT.getId());
                intent.putExtra("nameSender", MyApplication.USER_CURRENT.getFullName());
                intent.putExtra("msg", "");
                getActivity().sendBroadcast(intent);
            }
        }
    };
	
    /**
     * send broadcast
     * 
     * @author vuvt
     *
     */
	private class ListFriendsBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("ADD_FRIEND".equals(intent.getAction())) {
                User user = (User)intent.getSerializableExtra("user_add");
                int num = 0;
                for (User item : MyApplication.LIST_FRIENDS) {
                    if(!item.getEmail().equals(user.getEmail())) {
                        num++;
                    }
                }
                if (num == MyApplication.LIST_FRIENDS.size()) {
                    MyApplication.LIST_FRIENDS.add(user);
                    Message msg = toastHandler.obtainMessage(5);
                    toastHandler.sendMessage(msg);
                }
            } else if("DELETE_FRIEND".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getStringExtra("msg"));
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            } else if("GET_GROUP_ID".equals(intent.getAction())) {
                Message msg = toastHandler.obtainMessage(6);
                Bundle bun = new Bundle();
                bun.putString("idGroup", intent.getStringExtra("idGrp"));
                msg.setData(bun);
                toastHandler.sendMessage(msg);
                // add to group id
                MyApplication.GROUP_ID = intent.getStringExtra("idGrp");
                // add one id to list id
                String listId = intent.getStringExtra("idList");
                String[] li = listId.split(",");
                MyApplication.LIST_ID_EACH_GROUP.put(Integer.parseInt(MyApplication.GROUP_ID), new ArrayList<Integer>());
                for (String string : li) {
                    MyApplication.LIST_ID_EACH_GROUP.get(Integer.parseInt(MyApplication.GROUP_ID)).add(Integer.parseInt(string));
                }
            }
        }
	}
}
